<?php
error_reporting(0);
class Hd_Mysql {

	private $Hd_db;
	private static $Hd_Instance;
	
	private function __construct($config) {
		if(empty($config)){
			$config=array(
				"DBHOST"=>"localhost",
				"DBUSER"=>"root",
				"DBPASSWORD"=>"root",
				"DBNAME"=>"name",
				"ERROR"=>"mysql error"
			);
		}
		$this->Hd_db=mysql_connect($config['DBHOST'],$config['DBUSER'],$config['DBPASSWORD'])or die($config['ERROR']);
		mysql_select_db($config['DBNAME']);
		mysql_set_charset("utf8");
	}
	
	public static function Hd_MysqlClose($Hd_db){
		mysql_close($Hd_db);
	}
	
	public static function Hd_GetInstance($config){
		if(!(self::$Hd_Instance instanceof self)){    
       		self::$Hd_Instance = new self($config);    
    	}  
    	return self::$Hd_Instance;
	}

	public function Hd_Insert($dbtable,$values) {
		foreach($values as $key=>$value):
			$sql_keys[]="`".$key."`";
			$sql_values[]=(is_numeric($value))?($value):("'".$value."'");
		endforeach;
		$sql_key=implode(',',$sql_keys);
		$sql_value=implode(',',$sql_values);
		$Hd_Sql="INSERT INTO `$dbtable` ( $sql_key ) VALUES ( $sql_value );";
		//return $Hd_Sql;
		$Hd_Result=mysql_query($Hd_Sql);
		return mysql_insert_id();
	}
	
	public function Hd_Select($dbtable,$field,$where="",$limit="0,10") {
		$Hd_Sql="SELECT $field FROM `$dbtable` ";
		$Hd_Sql.=$this->Hd_Where($where);
		$Hd_Sql.=" limit $limit";
		$Hd_Sql.=";";
		//return $Hd_Sql;
		$Hd_Result=mysql_query($Hd_Sql);
		if(!$Hd_Result){
			exit("error");
		}
		while($row=mysql_fetch_array($Hd_Result)){
			$Hd_Row[]=$row;
		}
		$limits=explode(',',$limit);
		if($limits[1]==1){
			return $Hd_Row[0];
		}
		return $Hd_Row;
	}
	
	public function Hd_Update($dbtable,$fields,$where) {
		$Hd_Sql="UPDATE `$dbtable` set ";
		foreach($fields as $key=>$row):
			$Hd_Sqls[]="`$key`='$row'";
		endforeach;
		$Hd_Sql.=implode(' , ',$Hd_Sqls);
		$Hd_Sql.=$this->Hd_Where($where);
		$Hd_Sql.=";";
		//return $Hd_Sql;
		$Hd_Result=mysql_query($Hd_Sql);
		return $Hd_Result?TRUE:FALSE;
	}
	
	public function Hd_Delete($dbtable,$where) {
		$Hd_Sql="DELETE FROM `$dbtable` ";
		$Hd_Sql.=$this->Hd_Where($where);
		$Hd_Sql.=";";
		//return $Hd_Sql;
		$Hd_Result=mysql_query($Hd_Sql);
		return $Hd_Result?TRUE:FALSE;
	}
	
	private function Hd_Where($where) {
		if(!empty($where)){
			$Hd_Sql.=" WHERE ";
			if(is_array($where)){
				foreach($where as $key=>$row):
					$rows=(is_numeric($row))?($row):("'".$row."'");
					$Hd_Sqls[]="`$key`=$rows";
				endforeach;
				$Hd_Sql.=implode(' and ',$Hd_Sqls);
			}else{
				$Hd_Sql.="$where";
			}
		}
		return $Hd_Sql;
	}
	
	private function Hd_Query($Hd_Sql) {
		$Hd_Result=mysql_query($Hd_Sql);
		while($row=mysql_fetch_array($Hd_Result)){
			$Hd_Row[]=$row;
		}
		return $Hd_Row;
	}
}
?>